package com.sgb.goods.api;

import com.sgb.goods.utils.StringUtils;
import com.sgb.goods.utils.base.GoodsSdk;
import com.sgb.goods.utils.module.GoodsModule;
import com.swgk.core.base.api.ICallBack;
import com.swgk.core.base.model.entity.BaseEntity;
import com.swgk.core.dialog.DialogHelper;
import com.swgk.core.event.EventConstant;
import com.swgk.core.event.LoginTokenEvent;
import com.swgk.core.util.MLog;
import com.swgk.core.util.MToast;
import com.swgk.core.util.SharedPreferenceUtil;

import org.greenrobot.eventbus.EventBus;

import retrofit2.Call;

/**
 * 重写 ICallBack 实现商品 module 自己的网络失败处理
 * 商品 module 所有的网络回调应该使用此类
 *
 * @author cyj
 */
public abstract class GoodsCallBack<T> extends ICallBack<T> {

    private boolean isAllowShowNextToast = true;

    @Override
    public void onFailure(Call call, Throwable t) {
        if (isAllowShowNextToast) {
            MLog.e("网络链接不稳定，请稍后重试", "数据打印: " + call.request().toString() + "\n" + t.getMessage());
            MToast.showToast(GoodsSdk.getApplication(), "网络链接不稳定，请稍后重试");
            t.printStackTrace();
            DialogHelper.dismissProgressDialog();
            // {"state":"fail","code":1,"errCode":null,"msg":"服务连接超时","data":null}
            //{"msg":"status 401 reading LoginUser#user()","code":500,"data":null,"payload":"","errCode":539999,"state":"fail"}

        }
    }

    @Override
    final public void onFailureWithEntity(BaseEntity entity) {
        if (null != entity && !StringUtils.isEmpty(entity.getMsg())) {
            isAllowShowNextToast = false;
            MToast.showToast(GoodsSdk.getApplication(), entity.getMsg() + "");
//            if (entity.getMsg().contains("身份验证失败")) {
//                cleanTokenInfo();
//            }
        }
    }

    /**
     * 清除登录信息
     */
    private void cleanTokenInfo() {
        SharedPreferenceUtil.getInstance().saveData(SharedPreferenceUtil.LOGIN_TOKEN, "");
        SharedPreferenceUtil.getInstance().saveData(SharedPreferenceUtil.LOGIN_PC_TOKEN, "");
        SharedPreferenceUtil.getInstance().saveData(SharedPreferenceUtil.resourceAPPToken, "");
        SharedPreferenceUtil.getInstance().saveData(SharedPreferenceUtil.resourcePCToken, "");
        GoodsModule.getInstance().call1("jumpVerificationCodeLoginActivity", 1022);
    }
}
